package com.tim.app.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.widget.EmptyLayout;
import com.application.library.widget.loadmore.LoadMoreContainer;
import com.application.library.widget.loadmore.LoadMoreHandler;
import com.application.library.widget.loadmore.LoadMoreRecycleViewContainer;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.server.api.API_App;
import com.tim.app.server.api.API_Found;
import com.tim.app.server.entry.Topic;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.server.result.TopicListResult;
import com.tim.app.ui.activity.selected.TopicDetailActivity;
import com.tim.app.ui.adapter.selceted.GoodAtTopicAdapter;
import com.tim.app.util.SoftKeyboardUtil;
import com.tim.app.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;


/**
 * 搜索话题
 */
public class SearchTopicActivity extends BaseActivity implements BaseRecyclerAdapter.OnItemClickListener, TextWatcher, LoadMoreHandler {

    public static final String TAG = "SearchTopicActivity";

    private EditText etSearch;
    private ImageButton ibDelete;

    private LoadMoreRecycleViewContainer load_more;
    private WrapRecyclerView wrvTopic;
    private EmptyLayout emptyLayout;

    private List<Topic> dataList;
    private GoodAtTopicAdapter adapter;

    private int pageNumber = 1;

    public static void start(Context context) {
        Intent intent = new Intent(context, SearchTopicActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_search_topic;
    }


    @Override
    public void initView() {
        etSearch = (EditText) findViewById(R.id.etSearch);
        ibDelete = (ImageButton) findViewById(R.id.ibDelete);

        load_more = (LoadMoreRecycleViewContainer) findViewById(R.id.load_more);
        wrvTopic = (WrapRecyclerView) findViewById(R.id.wrvTopic);
        wrvTopic.setOverScrollMode(View.OVER_SCROLL_NEVER);

        load_more.useDefaultFooter(View.GONE);
        load_more.setAutoLoadMore(true);
        load_more.setLoadMoreHandler(this);
        emptyLayout = new EmptyLayout(this, load_more);
        emptyLayout.showContent();
        emptyLayout.setEmptyDrawable(R.drawable.ic_empty_search);
        emptyLayout.setEmptyText("没有找到你想要的内容", "");
        emptyLayout.setEmptyButtonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                emptyLayout.showLoading();
            }
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        wrvTopic.setLayoutManager(layoutManager);

        findViewById(R.id.ibBack).setOnClickListener(this);
        findViewById(R.id.ibDelete).setOnClickListener(this);

        dataList = new ArrayList<>();
        adapter = new GoodAtTopicAdapter(this, dataList, true);
        adapter.setOnItemClickListener(this);
        wrvTopic.setAdapter(adapter);
        etSearch.addTextChangedListener(this);

        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                switch (actionId) {
                    case EditorInfo.IME_ACTION_SEARCH:
                        String keyWords = etSearch.getText().toString().trim();
                        search(keyWords, false);
                        break;
                }
                return true;
            }
        });
    }

    StringResponseCallback refreshCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                if (dataList != null) {
                    dataList.clear();
                }
                TopicListResult result = new Gson().fromJson(resultValue, TopicListResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes() && null != result.getRes().getArraylist()) {
                        if (null != result.getRes().getArraylist().getResult()) {
                            dataList.addAll(result.getRes().getArraylist().getResult());
                            adapter.notifyDataSetChanged();
                        }
                        pageNumber = result.getRes().getArraylist().getCurrentPageNo();
                        if (pageNumber != result.getRes().getArraylist().getTotalPageCount()) {
                            load_more.loadMoreFinish(false, true);
                        } else {
                            load_more.loadMoreFinish(false, false);
                        }
                    }
                }

                if (dataList == null || dataList.size() == 0) {
                    emptyLayout.showEmpty();
                } else {
                    emptyLayout.showContent();
                }
            } else {
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    StringResponseCallback moreCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                TopicListResult result = new Gson().fromJson(resultValue, TopicListResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes() && null != result.getRes().getArraylist()) {
                        if (null != result.getRes().getArraylist().getResult()) {
                            dataList.addAll(result.getRes().getArraylist().getResult());
                            adapter.notifyDataSetChanged();
                        }
                        pageNumber = result.getRes().getArraylist().getCurrentPageNo();
                        if (pageNumber != result.getRes().getArraylist().getTotalPageCount()) {
                            load_more.loadMoreFinish(false, true);
                        } else {
                            load_more.loadMoreFinish(false, false);
                        }
                    }
                }

            } else {
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    /**
     * 搜索
     *
     * @param keyWord
     */
    private void search(String keyWord, boolean isLoadmore) {
        if (TextUtils.isEmpty(keyWord)) {
            if (!isLoadmore) {
                pageNumber = 1;
                API_Found.ins().getRecommandTopic(TAG, pageNumber, AppKey.PAGE_SIZE, refreshCallback);
            } else {
                API_Found.ins().getRecommandTopic(TAG, pageNumber + 1, AppKey.PAGE_SIZE, moreCallback);
            }
        } else {
            if (!isLoadmore) {
                pageNumber = 1;
                API_App.ins().search(TAG, AppKey.SEARCH_TOPIC, keyWord, pageNumber, AppKey.PAGE_SIZE, refreshCallback);
            } else {
                API_App.ins().search(TAG, AppKey.SEARCH_TOPIC, keyWord, pageNumber + 1, AppKey.PAGE_SIZE, moreCallback);
            }
        }
    }

    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        String keyWord = etSearch.getText().toString();
        search(keyWord, true);
    }

    @Override
    public void initData() {
        search("", false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibDelete:
                etSearch.setText("");
                ibDelete.setVisibility(View.GONE);
                break;
            case R.id.ibBack:
                SoftKeyboardUtil.hideSoftKeyboard(etSearch);
                finish();
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (!TextUtils.isEmpty(etSearch.getText().toString())) {
            ibDelete.setVisibility(View.VISIBLE);
        } else {
            ibDelete.setVisibility(View.GONE);
        }
        search(etSearch.getText().toString(), false);
    }

    @Override
    public void onItemClick(View view, int position, long id) {
        TopicDetailActivity.start(this, dataList.get(position), false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(TAG);
        OkHttpUtils.getInstance().cancelTag(GoodAtTopicAdapter.TAG);
    }

}
